<template>
  <div class="product-page">
    <!-- 页面标题与操作按钮 -->
    <div class="page-header">
      <div class="page-title">
        <h2>商品管理</h2>
      </div>
      <div class="page-actions">
        <el-button type="primary" icon="el-icon-plus" @click="showAddProductDialog = true">添加商品</el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-area">
      <div class="search-form">
        <el-input 
          v-model="searchKeyword" 
          placeholder="搜索商品名称、SKU..." 
          prefix-icon="el-icon-search"
          clearable
          class="search-input"
        ></el-input>
        
        <el-select 
          v-model="productCategoryFilter" 
          placeholder="商品分类" 
          clearable
          class="category-select"
        >
          <el-option label="全部分类" value=""></el-option>
          <el-option 
            v-for="category in categories" 
            :key="category.id" 
            :label="category.name" 
            :value="category.id"
          ></el-option>
        </el-select>
        
        <div class="search-buttons">
          <el-button type="primary" @click="handleSearchProducts">
            <i class="el-icon-search"></i> 搜索
          </el-button>
          <el-button @click="resetSearch">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </div>
      </div>
    </div>

    <!-- 商品表格区域 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="productTableData"
        style="width: 100%"
        border
        stripe
        highlight-current-row
        :header-cell-style="{
          backgroundColor: '#f5f7fa', 
          color: '#606266',
          fontWeight: 'bold',
          height: '50px'
        }"
      >
        <el-table-column prop="id" label="商品ID" width="150" align="center"></el-table-column>
        
        <el-table-column label="商品图片" width="120" align="center">
          <template #default="scope">
            <el-image
             preview-teleported="true"
              style="width: 80px; height: 80px; border-radius: 4px; border: 1px solid #eee; object-fit: cover;"
              :src="scope.row.coverImage || 'https://via.placeholder.com/80'"
              fit="cover"
              :preview-src-list="[scope.row.coverImage]"
            >
              <template #error>
                <div class="image-placeholder">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        
        <el-table-column label="商品信息" min-width="250">
          <template #default="scope">
            <div class="product-info">
              <div class="product-name">{{ scope.row.name }}</div>
              <div class="product-meta">
                <span class="product-sku">SKU: {{ scope.row.sku }}</span>
                <span v-if="scope.row.brand" class="product-brand">品牌: {{ scope.row.brand }}</span>
              </div>
              <div class="product-tags" v-if="scope.row.isNew || scope.row.isHot || scope.row.isRecommended">
                <el-tag size="mini" type="success" v-if="scope.row.isNew">新品</el-tag>
                <el-tag size="mini" type="danger" v-if="scope.row.isHot">热销</el-tag>
                <el-tag size="mini" type="warning" v-if="scope.row.isRecommended">推荐</el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="价格" width="120" align="center">
          <template #default="scope">
            <div class="price-info">
              <div class="current-price">¥{{ scope.row.price }}</div>
              <div class="original-price" v-if="scope.row.originalPrice && scope.row.originalPrice > scope.row.price">
                ¥{{ scope.row.originalPrice }}
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="categoryName" label="分类" width="120" align="center">
          <template #default="scope">
            <el-tag size="small" effect="plain" v-if="scope.row.categoryName">{{ scope.row.categoryName }}</el-tag>
            <span v-else class="no-data">未分类</span>
          </template>
        </el-table-column>
        
        <!-- <el-table-column prop="sales" label="销量" width="100" align="center">
          <template #default="scope">
            <span class="sales-count">{{ scope.row.sales || 0 }}</span>
          </template>
        </el-table-column> -->
        
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <div class="status-wrapper">
              <el-switch
                v-model="scope.row.isPublished"
                active-color="#1890ff"
                inactive-color="#dcdfe6"
                @change="() => handlePublishProduct(scope.row.id, scope.row.isPublished)"
              ></el-switch>
              <div class="status-text">{{ scope.row.isPublished ? '已上架' : '已下架' }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button type="primary" size="mini" @click="prepareEditProduct(scope.row)">
                <i class="el-icon-edit"></i> 编辑
              </el-button>
              <el-popconfirm
                title="确定删除该商品吗？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="handleDeleteProduct(scope.row.id)"
              >
                <template #reference>
                  <el-button type="danger" size="mini">
                    <i class="el-icon-delete"></i> 删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
        
        <template #empty>
          <div class="empty-state">
            <i class="el-icon-goods"></i>
            <p>暂无商品数据</p>
            <p class="empty-tip">您可以添加新商品或调整搜索条件</p>
            <div class="empty-actions">
              <el-button type="primary" @click="showAddProductDialog = true">添加商品</el-button>
              <el-button @click="resetSearch">重置筛选</el-button>
            </div>
          </div>
        </template>
      </el-table>
      
      <!-- 分页区域 -->
      <div class="pagination-area">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalProducts"
        ></el-pagination>
      </div>
    </div>

    <!-- 添加商品对话框 -->
    <el-dialog title="添加新商品" v-model="showAddProductDialog" width="60%">
      <el-form :model="newProduct" label-width="120px" :rules="productRules" ref="productForm">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="newProduct.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="SKU" prop="sku">
          <el-input v-model="newProduct.sku" placeholder="请输入商品SKU"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="newProduct.price" :precision="2" :step="0.1" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input-number v-model="newProduct.originalPrice" :precision="2" :step="0.1" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="newProduct.categoryId" placeholder="请选择商品分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="newProduct.brand" placeholder="请输入品牌名称"></el-input>
        </el-form-item>
        <el-form-item label="商品封面" prop="coverImage">
          <div class="upload-box">
            <div class="upload-preview-container">
              <el-image 
                v-if="newProduct.coverImage" 
                :src="newProduct.coverImage" 
                fit="cover" 
                class="image-preview">
              </el-image>
              <div v-else class="upload-placeholder">
                <i class="el-icon-picture"></i>
                <span>暂无封面</span>
              </div>
            </div>
            <div class="upload-buttons">
              <el-upload
                class="upload-component"
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleCoverImageChange">
                <el-button type="primary" size="small">
                  <i class="el-icon-upload"></i> 选择封面图片
                </el-button>
              </el-upload>
              <el-button 
                v-if="newProduct.coverImage" 
                type="danger" 
                size="small" 
                @click="removeCoverImage">
                <i class="el-icon-delete"></i> 移除封面
              </el-button>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="商品图片集">
          <div class="image-gallery">
            <div class="image-list">
              <div v-for="(image, index) in productImages" :key="index" class="image-item">
                <el-image :src="image.url" fit="cover" class="gallery-image"></el-image>
                <div class="image-actions">
                  <el-button 
                    type="danger" 
                    icon="el-icon-delete" 
                    circle 
                    size="mini" 
                    @click="removeImage(index)">
                  </el-button>
                  <el-checkbox 
                    v-model="image.isMain" 
                    @change="handleMainImageChange(index)">
                    设为主图
                  </el-checkbox>
                </div>
              </div>
              <div class="upload-image-item">
                <el-upload
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="handleImageSelect"
                  multiple>
                  <div class="upload-trigger">
                    <i class="el-icon-plus"></i>
                    <span>添加图片</span>
                  </div>
                </el-upload>
              </div>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" v-model="newProduct.description" :rows="4" placeholder="请输入商品描述"></el-input>
        </el-form-item>
        <el-form-item label="特殊标记">
          <el-checkbox v-model="newProduct.isNew">新品</el-checkbox>
          <el-checkbox v-model="newProduct.isHot">热销</el-checkbox>
          <el-checkbox v-model="newProduct.isRecommended">推荐</el-checkbox>
          <el-checkbox v-model="newProduct.isPublished">上架</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddProductDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAddProduct" :loading="submitting">确认添加</el-button>
      </template>
    </el-dialog>

    <!-- 编辑商品对话框 -->
    <el-dialog title="编辑商品" v-model="showEditProductDialog" width="60%">
      <el-form :model="editingProduct" label-width="120px" :rules="productRules" ref="editProductForm">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="editingProduct.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="SKU" prop="sku">
          <el-input v-model="editingProduct.sku" placeholder="请输入商品SKU"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="editingProduct.price" :precision="2" :step="0.1" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input-number v-model="editingProduct.originalPrice" :precision="2" :step="0.1" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="editingProduct.categoryId" placeholder="请选择商品分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="editingProduct.brand" placeholder="请输入品牌名称"></el-input>
        </el-form-item>
        <el-form-item label="商品封面" prop="coverImage">
          <div class="upload-box">
            <div class="upload-preview-container">
              <el-image 
                v-if="editingProduct.coverImage" 
                :src="editingProduct.coverImage" 
                fit="cover" 
                class="image-preview">
              </el-image>
              <div v-else class="upload-placeholder">
                <i class="el-icon-picture"></i>
                <span>暂无封面</span>
              </div>
            </div>
            <div class="upload-buttons">
              <el-upload
                class="upload-component"
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleEditCoverImageChange">
                <el-button type="primary" size="small">
                  <i class="el-icon-upload"></i> 选择封面图片
                </el-button>
              </el-upload>
              <el-button 
                v-if="editingProduct.coverImage" 
                type="danger" 
                size="small" 
                @click="removeEditCoverImage">
                <i class="el-icon-delete"></i> 移除封面
              </el-button>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="商品图片集">
          <div class="image-gallery">
            <div class="image-list">
              <div v-for="(image, index) in editProductImages" :key="index" class="image-item">
                <el-image :src="image.url" fit="cover" class="gallery-image"></el-image>
                <div class="image-actions">
                  <el-button 
                    type="danger" 
                    icon="el-icon-delete" 
                    circle 
                    size="mini" 
                    @click="removeEditImage(index)">
                  </el-button>
                  <el-checkbox 
                    v-model="image.isMain" 
                    @change="handleEditMainImageChange(index)">
                    设为主图
                  </el-checkbox>
                </div>
              </div>
              <div class="upload-image-item">
                <el-upload
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="handleEditImageSelect"
                  multiple>
                  <div class="upload-trigger">
                    <i class="el-icon-plus"></i>
                    <span>添加图片</span>
                  </div>
                </el-upload>
              </div>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" v-model="editingProduct.description" :rows="4" placeholder="请输入商品描述"></el-input>
        </el-form-item>
        <el-form-item label="特殊标记">
          <el-checkbox v-model="editingProduct.isNew">新品</el-checkbox>
          <el-checkbox v-model="editingProduct.isHot">热销</el-checkbox>
          <el-checkbox v-model="editingProduct.isRecommended">推荐</el-checkbox>
          <el-checkbox v-model="editingProduct.isPublished">上架</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditProductDialog = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateProduct" :loading="submitting">保存修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import productApi, { IProductDto, IProductImageDto } from '../../api/product';
import categoryApi from '../../api/category';

// 商品列表相关
const products = ref<IProductDto[]>([]);
const totalProducts = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const sortBy = ref('id');
const sortDirection = ref('desc');
const loading = ref(false);
const searchKeyword = ref('');
const productCategoryFilter = ref('');

// 商品分类列表
const categories = ref([]);
const showAddProductDialog = ref(false);
const showEditProductDialog = ref(false);
const submitting = ref(false);

// 商品表格数据（带分页和过滤）
const productTableData = computed(() => products.value);

// 商品图片相关
const productImages = ref<{url: string, file?: File, isMain: boolean}[]>([]);
const editProductImages = ref<{url: string, id?: number, file?: File, isMain: boolean}[]>([]);
const coverImageFile = ref<File | null>(null);
const editCoverImageFile = ref<File | null>(null);

// 表单验证规则
const productRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  sku: [
    { required: true, message: '请输入商品SKU', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ]
};

// 新商品表单
const newProduct = reactive<IProductDto>({
  name: '',
  sku: '',
  price: 0,
  originalPrice: 0,
  stock: 0,
  categoryId: 0,
  brand: '',
  description: '',
  coverImage: '',
  isPublished: false,
  isRecommended: false,
  isNew: false,
  isHot: false
});

// 编辑商品表单
const editingProduct = reactive<IProductDto>({
  id: '',
  name: '',
  sku: '',
  price: 0,
  originalPrice: 0,
  stock: 0,
  categoryId: 0,
  brand: '',
  description: '',
  coverImage: '',
  isPublished: false,
  isRecommended: false,
  isNew: false,
  isHot: false
});

// 获取商品列表
const fetchProducts = async () => {
  loading.value = true;
  
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value - 1, // 后端页码从0开始
      size: pageSize.value,
      sort: sortBy.value,
      direction: sortDirection.value
    };
    
    // 添加搜索条件
    if (searchKeyword.value && searchKeyword.value.trim()) {
      console.log('添加搜索关键词:', searchKeyword.value);
      params.keyword = searchKeyword.value.trim();
    }
    
    // 添加分类过滤
    if (productCategoryFilter.value) {
      console.log('添加分类过滤:', productCategoryFilter.value);
      params.categoryId = productCategoryFilter.value;
    }
    
    console.log('开始获取商品列表数据，参数:', params);
    
    // 根据是否有搜索关键词选择API
    let result;
    if (params.keyword) {
      // 使用搜索API
      result = await productApi.searchProducts(params.keyword, params);
    } else {
      // 使用普通分页API
      result = await productApi.getProductsPage(params);
    }
    
    console.log('API响应数据:', result);
    
    // 如果是使用了新的axios拦截器，result就是data，不需要再访问result.data
    const data = result.data;
    products.value = data.content;
    totalProducts.value = data.totalElements;
    console.log('处理后的商品数据:', products.value);
    
    if (products.value.length === 0 && totalProducts.value > 0 && currentPage.value > 1) {
      // 如果当前页没有数据，但总数大于0，说明可能是页码超出范围，回到第一页
      currentPage.value = 1;
      fetchProducts();
    }
  } catch (error) {
    console.error('获取商品列表出错:', error);
    ElMessage.error(`网络错误: ${error.message || '未知错误'}`);
    // 如果API请求出错，使用模拟数据作为备用
    useMockData();
  } finally {
    loading.value = false;
  }
};

// 备用：使用模拟数据
const useMockData = () => {
  const mockData = {
    content: [
      {
        id: 'P001',
        name: '奢华滋养面霜',
        sku: 'SKU001',
        price: 299.00,
        originalPrice: 399.00,
        categoryId: 1,
        categoryName: '护肤品',
        brand: '美丽秘方',
        description: '深层滋养，提升肌肤活力',
        coverImage: 'https://via.placeholder.com/200x200?text=Face+Cream',
        isPublished: true,
        isRecommended: true,
        isNew: true,
        isHot: false,
        sales: 128
      },
      {
        id: 'P002',
        name: '清透防晒乳',
        sku: 'SKU002',
        price: 159.00,
        originalPrice: 189.00,
        categoryId: 1,
        categoryName: '护肤品',
        brand: '美丽秘方',
        description: '轻薄防护，不油腻',
        coverImage: 'https://via.placeholder.com/200x200?text=Sunscreen',
        isPublished: true,
        isRecommended: false,
        isNew: false,
        isHot: true,
        sales: 89
      },
      {
        id: 'P003',
        name: '丝绒雾面口红',
        sku: 'SKU003',
        price: 128.00,
        originalPrice: 158.00,
        categoryId: 2,
        categoryName: '彩妆',
        brand: '美妆物语',
        description: '持久显色，不易脱妆',
        coverImage: 'https://via.placeholder.com/200x200?text=Lipstick',
        isPublished: true,
        isRecommended: true,
        isNew: false,
        isHot: true,
        sales: 256
      }
    ],
    totalElements: 3
  };
  
  console.log('使用模拟数据');
  products.value = mockData.content;
  totalProducts.value = mockData.totalElements;
};

// 获取商品分类列表
const fetchCategories = async () => {
  try {
    // 使用商品分类API
    const result = await categoryApi.getAllCategories();
    console.log('获取分类API响应:', result);
    
    categories.value = result.data;
    console.log('获取到的分类数据:', categories.value);
  } catch (error) {
    console.error('获取分类列表出错:', error);
    ElMessage.error('获取分类列表失败，使用默认分类');
    // 使用备用的模拟分类数据
    categories.value = [
      { id: 1, name: '护肤品' },
      { id: 2, name: '彩妆' },
      { id: 3, name: '香水' },
      { id: 4, name: '美容工具' }
    ];
  }
};

// 处理封面图片选择
const handleCoverImageChange = (file: any) => {
  const isImage = file.raw.type.startsWith('image/');
  const isLt5M = file.raw.size / 1024 / 1024 < 5;
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return;
  }
  
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return;
  }
  
  // 创建预览URL
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = () => {
    newProduct.coverImage = reader.result as string;
    coverImageFile.value = file.raw;
  };
};

// 移除封面图片
const removeCoverImage = () => {
  newProduct.coverImage = '';
  coverImageFile.value = null;
};

// 处理图片选择
const handleImageSelect = (file: any) => {
  const isImage = file.raw.type.startsWith('image/');
  const isLt5M = file.raw.size / 1024 / 1024 < 5;
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return;
  }
  
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return;
  }
  
  // 创建预览URL
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = () => {
    productImages.value.push({
      url: reader.result as string,
      file: file.raw,
      isMain: productImages.value.length === 0 // 第一张图片默认为主图
    });
  };
};

// 移除图片
const removeImage = (index: number) => {
  const removedImage = productImages.value.splice(index, 1)[0];
  
  // 如果删除的是主图，则将第一张图片设为主图
  if (removedImage.isMain && productImages.value.length > 0) {
    productImages.value[0].isMain = true;
  }
};

// 处理主图更改
const handleMainImageChange = (index: number) => {
  // 确保只有一张图片被设置为主图
  productImages.value.forEach((image, i) => {
    if (i !== index) {
      image.isMain = false;
    }
  });
};

// 编辑模式下的图片处理方法
const handleEditCoverImageChange = (file: any) => {
  const isImage = file.raw.type.startsWith('image/');
  const isLt5M = file.raw.size / 1024 / 1024 < 5;
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return;
  }
  
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return;
  }
  
  // 创建预览URL
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = () => {
    editingProduct.coverImage = reader.result as string;
    editCoverImageFile.value = file.raw;
  };
};

// 移除编辑模式下的封面图片
const removeEditCoverImage = () => {
  editingProduct.coverImage = '';
  editCoverImageFile.value = null;
};

// 编辑模式下处理图片选择
const handleEditImageSelect = (file: any) => {
  const isImage = file.raw.type.startsWith('image/');
  const isLt5M = file.raw.size / 1024 / 1024 < 5;
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return;
  }
  
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return;
  }
  
  // 创建预览URL
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = () => {
    editProductImages.value.push({
      url: reader.result as string,
      file: file.raw,
      isMain: editProductImages.value.length === 0 // 第一张图片默认为主图
    });
  };
};

// 移除编辑模式下的图片
const removeEditImage = (index: number) => {
  const removedImage = editProductImages.value.splice(index, 1)[0];
  
  // 如果删除的是主图，则将第一张图片设为主图
  if (removedImage.isMain && editProductImages.value.length > 0) {
    editProductImages.value[0].isMain = true;
  }
};

// 处理编辑模式下主图更改
const handleEditMainImageChange = (index: number) => {
  // 确保只有一张图片被设置为主图
  editProductImages.value.forEach((image, i) => {
    if (i !== index) {
      image.isMain = false;
    }
  });
};

// 获取商品图片列表
const fetchProductImages = async (productId: string) => {
  try {
    const response = await productApi.getProductImages(productId);
    const images = response.data || [];
    
    // 转换为本地图片格式
    editProductImages.value = images.map(img => ({
      url: img.imageUrl,
      id: img.id,
      isMain: img.main
    }));
  } catch (error) {
    console.error('获取商品图片失败:', error);
    ElMessage.error('获取商品图片失败');
  }
};

// 修改原有的添加商品方法，添加图片上传逻辑
const handleAddProduct = async () => {
  console.log('添加商品，当前表单数据:', newProduct);
  
  try {
    // 表单验证
    if (!newProduct.name) {
      ElMessage.error('请输入商品名称');
      return;
    }
    if (!newProduct.sku) {
      ElMessage.error('请输入商品SKU');
      return;
    }
    if (!newProduct.price || newProduct.price <= 0) {
      ElMessage.error('请输入有效的商品价格');
      return;
    }
    if (!newProduct.categoryId) {
      ElMessage.error('请选择商品分类');
      return;
    }
    
    submitting.value = true;
    
    // 先创建商品基本信息
    const result = await productApi.createProduct(newProduct);
    console.log('添加商品API响应:', result);
    
    const productId = result.data.id;
    
    // 上传封面图片
    if (coverImageFile.value) {
      try {
        const uploadResult = await productApi.uploadImage(coverImageFile.value);
        console.log('封面图片上传结果:', uploadResult);
        
        // 更新商品封面图片URL
        const coverImageUrl = uploadResult.data.fileDownloadUri;
        await productApi.updateProduct(productId, { ...result.data, coverImage: coverImageUrl });
      } catch (error) {
        console.error('上传封面图片失败:', error);
        ElMessage.warning('封面图片上传失败，但商品已创建成功');
      }
    }
    
    // 上传商品图片集
    if (productImages.value.length > 0) {
      const imagesToUpload = productImages.value.filter(img => img.file);
      
      for (const image of imagesToUpload) {
        try {
          if (image.file) {
            const uploadResult = await productApi.uploadProductImage(productId, image.file, image.isMain);
            console.log('商品图片上传结果:', uploadResult);
          }
        } catch (error) {
          console.error('上传商品图片失败:', error);
          ElMessage.warning('部分商品图片上传失败');
        }
      }
    }
    
    ElMessage.success('商品添加成功');
    showAddProductDialog.value = false;
    
    // 清空表单
    Object.keys(newProduct).forEach(key => {
      if (typeof newProduct[key] === 'boolean') {
        newProduct[key] = false;
      } else if (typeof newProduct[key] === 'number') {
        newProduct[key] = 0;
      } else {
        newProduct[key] = '';
      }
    });
    
    // 清空图片相关数据
    productImages.value = [];
    coverImageFile.value = null;
    
    // 刷新商品列表
    fetchProducts();
  } catch (error) {
    console.error('添加商品出错:', error);
    ElMessage.error(`添加商品错误: ${error.message || '未知错误'}`);
  } finally {
    submitting.value = false;
  }
};

// 修改原有的编辑前准备方法，添加图片加载逻辑
const prepareEditProduct = async (product: IProductDto) => {
  // 深拷贝商品对象，避免直接修改列表中的数据
  Object.keys(editingProduct).forEach(key => {
    if (key in product) {
      editingProduct[key] = product[key];
    }
  });
  
  // 重置图片相关数据
  editProductImages.value = [];
  editCoverImageFile.value = null;
  
  // 获取商品图片列表
  if (product.id) {
    await fetchProductImages(product.id);
  }
  
  showEditProductDialog.value = true;
};

// 修改原有的更新商品方法，添加图片上传逻辑
const handleUpdateProduct = async () => {
  console.log('更新商品，当前编辑数据:', editingProduct);
  
  try {
    // 表单验证
    if (!editingProduct.name || !editingProduct.sku || !editingProduct.price || !editingProduct.categoryId) {
      ElMessage.error('请完善商品信息');
      return;
    }
    
    submitting.value = true;
    
    // 先更新商品基本信息
    const productId = editingProduct.id!;
    const result = await productApi.updateProduct(productId, editingProduct);
    console.log('更新商品API响应:', result);
    
    // 上传新的封面图片（如果有）
    if (editCoverImageFile.value) {
      try {
        const uploadResult = await productApi.uploadImage(editCoverImageFile.value);
        console.log('封面图片上传结果:', uploadResult);
        
        // 更新商品封面图片URL
        const coverImageUrl = uploadResult.data.fileDownloadUri;
        await productApi.updateProduct(productId, { ...result.data, coverImage: coverImageUrl });
      } catch (error) {
        console.error('上传封面图片失败:', error);
        ElMessage.warning('封面图片上传失败，但商品已更新成功');
      }
    }
    
    // 上传新的商品图片（如果有）
    const newImages = editProductImages.value.filter(img => img.file);
    for (const image of newImages) {
      try {
        if (image.file) {
          const uploadResult = await productApi.uploadProductImage(productId, image.file, image.isMain);
          console.log('商品图片上传结果:', uploadResult);
        }
      } catch (error) {
        console.error('上传商品图片失败:', error);
        ElMessage.warning('部分新增商品图片上传失败');
      }
    }
    
    // 更新现有图片的主图状态
    const existingImages = editProductImages.value.filter(img => img.id);
    for (const image of existingImages) {
      if (image.id) {
        try {
          const imageDto: IProductImageDto = {
            id: image.id,
            productId: productId,
            imageUrl: image.url,
            main: image.isMain
          };
          await productApi.addProductImage(productId, imageDto);
        } catch (error) {
          console.error('更新商品图片状态失败:', error);
        }
      }
    }
    
    ElMessage.success('商品更新成功');
    showEditProductDialog.value = false;
    
    // 刷新商品列表
    fetchProducts();
  } catch (error) {
    console.error('更新商品出错:', error);
    ElMessage.error(`更新商品错误: ${error.message || '未知错误'}`);
  } finally {
    submitting.value = false;
  }
};

// 删除商品
const handleDeleteProduct = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？此操作不可逆', '删除确认', {
      type: 'warning',
      confirmButtonText: '确认删除',
      cancelButtonText: '取消'
    });
    
    const result = await productApi.deleteProduct(id);
    console.log('删除商品API响应:', result);
    
    ElMessage.success('商品删除成功');
    fetchProducts();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品出错:', error);
      ElMessage.error(`删除商品错误: ${error.message || '未知错误'}`);
    }
  }
};

// 发布/下架商品
const handlePublishProduct = async (id: string, isPublished: boolean) => {
  try {
    const result = await productApi.publishProduct(id, isPublished);
    console.log('发布/下架商品API响应:', result);
    
    ElMessage.success(isPublished ? '商品发布成功' : '商品已下架');
    fetchProducts();
  } catch (error) {
    console.error('发布/下架商品出错:', error);
    ElMessage.error(`操作错误: ${error.message || '未知错误'}`);
    // 出错时刷新列表，确保显示正确的状态
    fetchProducts();
  }
};

// 处理搜索商品
const handleSearchProducts = () => {
  console.log('搜索条件: 关键词=', searchKeyword.value, '分类=', productCategoryFilter.value);
  currentPage.value = 1; // 重置到第一页
  fetchProducts();
};

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = '';
  productCategoryFilter.value = '';
  currentPage.value = 1;
  fetchProducts();
};

// 分页处理方法
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchProducts();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchProducts();
};

onMounted(() => {
  // 获取商品分类列表
  fetchCategories();
  
  // 获取商品列表
  fetchProducts();
});
</script>

<style scoped>
/* 整体页面样式 */
.product-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.page-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
  font-weight: 600;
}

/* 搜索区域样式 */
.search-area {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.search-input {
  width: 300px;
}

.category-select {
  width: 200px;
}

.search-buttons {
  display: flex;
  gap: 10px;
}

/* 表格容器样式 */
.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 产品信息样式 */
.product-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.product-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.product-meta {
  display: flex;
  gap: 10px;
  color: #909399;
  font-size: 13px;
}

.product-tags {
  margin-top: 5px;
  display: flex;
  gap: 5px;
}

/* 价格信息样式 */
.price-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.current-price {
  font-weight: 600;
  color: #f56c6c;
  font-size: 16px;
}

.original-price {
  color: #909399;
  text-decoration: line-through;
  font-size: 13px;
}

/* 状态开关样式 */
.status-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.status-text {
  font-size: 13px;
  color: #606266;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

/* 空状态样式 */
.empty-state {
  padding: 40px 0;
  text-align: center;
  color: #909399;
}

.empty-state i {
  font-size: 60px;
  color: #dcdfe6;
  margin-bottom: 20px;
}

.empty-tip {
  margin-top: 10px;
  font-size: 14px;
  color: #c0c4cc;
}

.empty-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

/* 分页区域样式 */
.pagination-area {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

/* 上传组件样式 */
.upload-box {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.upload-preview-container {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background-color: #fafafa;
}

.image-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #8c939d;
}

.upload-placeholder i {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 图片画廊样式 */
.image-gallery {
  width: 100%;
}

.image-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 16px;
}

.image-item {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: transform 0.3s;
}

.image-item:hover {
  transform: translateY(-5px);
}

.gallery-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  display: block;
}

.image-actions {
  padding: 8px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  background-color: #fff;
}

.upload-image-item {
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  background-color: #fafafa;
  transition: all 0.3s;
}

.upload-image-item:hover {
  border-color: #409eff;
  color: #409eff;
}

.upload-trigger {
  text-align: center;
  color: #8c939d;
}

.upload-trigger i {
  font-size: 28px;
  margin-bottom: 8px;
}

/* 对话框内表单样式优化 */
:deep(.el-dialog__body) {
  padding: 20px 30px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-input,
  .category-select {
    width: 100%;
  }
  
  .search-buttons {
    width: 100%;
    justify-content: flex-end;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .page-actions {
    width: 100%;
  }
  
  .upload-box {
    flex-direction: column;
  }
  
  .image-list {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  }
}

/* 无数据占位提示 */
.no-data {
  color: #c0c4cc;
  font-size: 13px;
}

/* 销量数字样式 */
.sales-count {
  font-weight: 600;
  color: #303133;
}

/* 鼠标悬停图片放大效果 */
.el-image {
  transition: transform 0.3s;
}

.el-image:hover {
  transform: scale(1.05);
}

/* 图片占位样式 */
.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #c0c4cc;
  background-color: #f5f7fa;
}
</style> 